package com.serkol.driving.learning;


import com.serkol.constant.AuthConstant;
import com.serkol.driving.learning.entity.LoginLog;
import com.serkol.driving.learning.service.LoginLogService;
import com.serkol.utils.LangValidUtils;
import com.serkol.utils.TokenUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@Configuration
@WebFilter(filterName = "myFilter",urlPatterns = "/*")
public class ApplicationFilter implements Filter {
    @Autowired
    private LoginLogService logService;
    private com.serkol.component.TokenUtils tokenUtils;
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request=(HttpServletRequest) servletRequest;
        HttpServletResponse response=(HttpServletResponse) servletResponse;
        System.out.println("PATH:"+request.getServletPath());
      //  System.out.println("METHOD:"+request.getMethod());
      if (request.getHeader("Access-Control-Request-Method") != null && "OPTIONS".equals(request.getMethod())) {
            // CORS "pre-flight" request
            response.addHeader("Access-Control-Allow-Origin", "*");
            response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
            response.setHeader("Access-Control-Allow-Headers", "x-requested-with,content-type,Authorization,language");
            response.addHeader("Access-Control-Max-Age", "1800");//30 min
       }
        String authorization = request.getHeader("Authorization");
      System.out.println("Authorization:"+authorization);
        String language = request.getHeader("language");
        System.out.println("language:"+language);

        if(StringUtils.isNotEmpty(language)){
            if(LangValidUtils.getValid(language,"ug")){
                AuthConstant.setLanguage("zh-UG");
            }else{
                AuthConstant.setLanguage("zh-CN");
            }
         //   AuthConstant.setLanguage(language);
        }else{
            AuthConstant.setLanguage("zh-CN");
        }

        if(StringUtils.isNotEmpty(authorization)){
            LoginLog auth = TokenUtils.getAuth(authorization);
           System.out.println(auth);
            if(auth!=null){
                String cliectIp = getCliectIp(request);
                tokenUtils = new com.serkol.component.TokenUtils(logService);
                boolean token = tokenUtils.isToken(authorization);
                if(!token){
                    AuthConstant.setLoginLog(null);
                }
            }
        }else{
            AuthConstant.setLoginLog(null);
        }
        filterChain.doFilter(request,response);
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }

    /**
     * 获取客户端ip地址
     *
     * @param request
     * @return
     */
    public static String getCliectIp(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.trim() == "" || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.trim() == "" || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.trim() == "" || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }

        // 多个路由时，取第一个非unknown的ip
        final String[] arr = ip.split(",");
        for (final String str : arr) {
            if (!"unknown".equalsIgnoreCase(str)) {
                ip = str;
                break;
            }
        }
        return ip;
    }
}

